//
//  DailyViewController.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/25.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

/*
 * 潮风尚
 *
 */

#import "DailyViewController.h"
#import "DailyHeader.h"
#import "DailyPullLayout.h"
#import "DailyCollectionCell.h"
#import "DailyDetailViewController.h"

#import "AsyncGETConnection.h"
#import "ArticleModel.h"
#import "NightMode.h"

#import "NetWorkNotify.h"
#import "GiFHUD.h"

@interface DailyViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,DailyHeaderDelegate>
@property (nonatomic,retain) NSDictionary * collectionDic;    // 包含了collectionArray和发布日期和标题
@property (nonatomic,retain) NSMutableArray * collectionArray;
@property (nonatomic,retain) UICollectionView * collection ;
@property (nonatomic,retain) DailyHeader * header;
@end

@implementation DailyViewController
-(void)dealloc{
    [_collectionArray release];
    [_collection release];
    [_collectionDic release];
    [_header release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.collectionArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [GiFHUD setGifWithImageName:@"33333333333.gif"];
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
    [self loadModelFromLocal];

}
// 首先从文件夹读取
-(void)loadModelFromLocal{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    // 把大信息字典从文件夹取出
    NSString * dicPath = [NSString stringWithFormat:@"%@/daily/infodic",path];
    self.collectionDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
    
    NSArray * listArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/%@/model",path,@"daily"] error:nil];
    for (NSString * fileName in listArray) { // fileName为每个文件的文件名
        NSData * data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/daily/model/%@",path,fileName]];
        ArticleModel * model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [self.collectionArray addObject:model];
    }
    
    if(_collectionArray.count != 0) // 如果文件中没有文件就不创建collection，否则瀑布流会越界
        [self createCollection];
    
    [self reloadDataFromNetwork];
}
// 如果没有网，显示没有网络
-(void)showNetworkNotifyView{
    for (UIView * view in [self.view subviews]) {
        // 如果父视图中有mb，则删除mb，显示没网，并直接返回，如果没有，不进行任何操作
        if([view isKindOfClass:[GiFHUD class]]){
            [view removeFromSuperview];
            [self.view addSubview: [NetWorkNotify showNetworkNotify]];
            return;
        }
    }
   
}
-(void)reloadDataFromNetwork{
//    MBProgressHUD * mb = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    [self.view addSubview:mb];
//    mb.userInteractionEnabled = NO;
//    mb.labelText = @"加载中...";
//    [mb show:YES];
    [GiFHUD show];
    // 8秒后如果mb还在父视图，就说明没加载出来，那么显示没有网络，并从父视图删除
    [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(showNetworkNotifyView) userInfo:nil repeats:NO];
//    [mb release];
    
    // 格式化日期
    NSDate * today = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString * dateString = [dateFormatter stringFromDate:today];
    [dateFormatter release];
    
    NSString * urlString = [NSString stringWithFormat: @"http://mrosevision.sinaapp.com/mfashion_api_v200.php?ac=getflowbydate&reqdate=%@%2000%3A01%%3A00&did=640%%2C1136%%2CiPhone5%%2C2&format=json&dim=02%%3A00%%3A00%%3A00%%3A00%%3A00&dic=AppStore&div=2.1.0&djb=1&diu=0F607264FC6318A92B9E13C65DB7CD3C",dateString];
    [AsyncGETConnection asyncConnectionWithURLString:urlString parmaters:nil block:^(NSData *data) {
        self.collectionDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
//        [mb removeFromSuperview];
        
        [self.collectionArray removeAllObjects];
        NSInteger i = 0;
        
        // 把大信息字典存入文件夹
        NSString * dicPath = [NSString stringWithFormat:@"%@/daily/infodic",[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject]];
        [_collectionDic writeToFile:dicPath atomically:YES];
        
        // 因为除了存model，还需要存一个字典，不能在一个文件夹，否则字典会被遍历到，所以要给model们单独放在一个文件夹
        for (NSDictionary * subDic in [_collectionDic objectForKey:@"article"]) {
            ArticleModel * model = [[ArticleModel alloc] init];
            [model setValuesForKeysWithDictionary:subDic];
            [self.collectionArray addObject:model];
            
            NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
            // 存入每个model的文件
            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
            path = [NSString stringWithFormat:@"%@/daily/model/%.2ld",path,(long)i]; // 要按照加入的顺序命名，而不能按照id命名，会造成读取顺序不一致
            [data writeToFile:path atomically:YES];
            i++;
            
            [model release];
            [GiFHUD dismiss];
        }
        // 如果collection是空而且有网，那么就创建collection；如果有网不是空，直接刷新
        if(_collection == nil){
            [self createCollection];
        }
        else{
//            [_collection reloadData];
            
            // 如果从网上加载数据完毕，全部重新创建，方式刷新数据后导致数据不一致，瀑布流crash
            [_collection removeFromSuperview];
            [self createCollection];
            [self createHeaderView];
        }
        
        
        if(_header == nil) // 在有网的情况下，如果header为空就创建header
            [self createHeaderView];
    }];
    
    if(_collectionDic != nil){ // 如果字典为空就创建header
        [self createHeaderView];
    }
}
-(void)createCollection{
    DailyPullLayout  * layout = [[[DailyPullLayout alloc] init]autorelease];
    // 前十个元素不属于collection的cell
    NSMutableArray * realArr = [NSMutableArray array];
    for (int i = 8; i<_collectionArray.count; i++) {
        [realArr addObject:[_collectionArray objectAtIndex:i]];
    }
    layout.dicArr = realArr;

    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20-49) collectionViewLayout:layout];
    _collection.bounces = YES;
    _collection.backgroundColor = [UIColor clearColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:[DailyCollectionCell class] forCellWithReuseIdentifier:@"normalcell"];
    [self.view addSubview:_collection];
    [_collection release];
}
// 创建一个显示在collection上的视图
-(void)createHeaderView{
    self.header = [[DailyHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 260+self.view.frame.size.width/2)];
    _header.delegate = self;
    [_header setHeaderWithDic:_collectionDic modelArray:_collectionArray]; // 将最外层的字典和里面的数组传给header
    [_collection addSubview:_header];
    [_header release];
}
#pragma mark - collectionView协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(_collectionArray.count == 0) return 0;
    return _collectionArray.count - 8;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DailyCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"normalcell" forIndexPath:indexPath];
    ArticleModel * model = [_collectionArray objectAtIndex:indexPath.item+8];
    [cell setCellWithModel:model];
    return cell;
}
// 点击item进入详情
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ArticleModel * model = [_collectionArray objectAtIndex:indexPath.item + 8];
    [self enterDetailWithModel:model];
}
#pragma mark - DailyHeader协议
-(void)enterDetailWithModel:(ArticleModel *)model{
    DailyDetailViewController * detail = [[DailyDetailViewController alloc] initWithModel:model];
    [self presentViewController:detail animated:YES completion:^{
        
    }];
    [detail release];
}
#pragma mark - 视图将要出现根据是否是夜间模式设置view
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.view setNeedsDisplay];
    self.navigationController.navigationBar.hidden = YES;
    _header.dateLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    _header.titleLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];

    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
}

// 状态栏为白色
- (UIStatusBarStyle)preferredStatusBarStyle{
    return [NightMode nightModeON]?UIStatusBarStyleLightContent:UIStatusBarStyleDefault;
}
@end
